<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="资源类型" prop="type">
        <el-select v-model="queryParams.type" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option label="养老机构" value="0"></el-option>
          <el-option label="服务企业" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="所在区域" prop="region1Id">
        <el-select v-model="queryParams.regionId" clearable
                   placeholder="请选择区域">
          <el-option label="全部" value=""></el-option>
          <el-option
            v-for="region1 in regionTree"
            :key="region1.id"
            :label="region1.name"
            :value="region1.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资源名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入养老资源名称"
          clearable
          @keyup.enter.native="handleQuery"/>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['health:healthResource:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['health:healthResource:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['health:healthResource:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['health:healthResource:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="healthResourceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" width="55" align="center" prop="id"/>
      <el-table-column label="类型" width="80" align="center" prop="type">
        <template slot-scope="scope">
          <span>{{ scope.row.type == 0 ? '养老机构' : '服务企业' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name"/>
      <el-table-column label="封面图片" align="center" prop="cover" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.cover" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="简介" align="center" prop="brief">
        <!--文字太长，只保留两行，多余的显示省略号-->
        <template slot-scope="scope">
          <el-tooltip :content="scope.row.brief" placement="top">
            <div style="
                overflow: hidden;
                display: -webkit-box;
                text-overflow: ellipsis;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                white-space: normal;
              ">
              {{ scope.row.brief }}
            </div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="资源电话" align="center" prop="phone"/>
      <el-table-column label="所在区域" align="center" prop="regionId">
        <template slot-scope="scope">
          <span>{{ region1Name(scope.row.regionId) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="地址" align="center" prop="address"/>
      <el-table-column label="联系人" align="center" prop="contact"/>
      <el-table-column label="床位数" align="center" prop="bedAmount">
        <template slot-scope="scope">
          <span>{{ scope.row.type==0 ? scope.row.bedAmount : '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="床位费" align="center" prop="bedFee">
        <template slot-scope="scope">
          <span>{{ scope.row.type==0 ? scope.row.bedFee : '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="护理费" align="center" prop="nursingFee">
        <template slot-scope="scope">
          <span>{{ scope.row.type==0 ? scope.row.nursingFee : '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-row>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['health:healthResource:edit']"
            >修改
            </el-button>
          </el-row>

          <el-row>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['health:healthResource:remove']"
            >删除
            </el-button>
          </el-row>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资源管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入养老资源名称"/>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="资源类型" prop="type">
              <el-radio-group v-model="form.type">
                <el-radio :label="0">养老机构</el-radio>
                <el-radio :label="1">服务企业</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所在区域" prop="regionId">
              <el-select v-model="form.regionId" clearable
                         placeholder="请选择区域">
                <el-option label="全部" value=""></el-option>
                <el-option
                  v-for="region1 in regionTree"
                  :key="region1.id"
                  :label="region1.name"
                  :value="region1.id">
                </el-option>
              </el-select>
            </el-form-item>
            <!--<el-form-item label="服务区域" prop="regionId">-->
            <!--  <el-cascader-->
            <!--    v-model="form.regionId"-->
            <!--    :options="regionTree"-->
            <!--    clearable-->
            <!--    :props="{ value: 'id',label: 'name', emitPath:false, expandTrigger: 'hover'}"-->
            <!--    :style="{ width:'100%' }"-->
            <!--  ></el-cascader>-->
            <!--  &lt;!&ndash;  使el-cascader 支持选择任意一级 checkStrictly: true   &ndash;&gt;-->
            <!--</el-form-item>-->
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="简介" prop="brief">
              <el-input v-model="form.brief" type="textarea"
                        rows="8"
                        placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="封面图片" prop="cover">
              <image-upload v-model="form.cover"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="6">
            <el-form-item label="联系人" prop="contact">
              <el-input v-model="form.contact" placeholder="请输入联系人"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入资源电话"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址"/>
            </el-form-item>
          </el-col>
        </el-row>

        <div v-show="form.type == 0">
          <el-form-item label="配套设施" prop="facilities">
            <el-checkbox-group v-model="facilitiesArr">
              <el-checkbox-button v-for="facility in facilityList"
                                  :label="facility"
                                  :key="facility"
                                  @change="handleFacilitiesChange"
              >{{ facility }}
              </el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>

          <el-row>
            <el-col :span="8">
              <el-form-item label="床位数(个)" prop="bedAmount">
                <el-input-number v-model="form.bedAmount"
                                 :precision="0"
                                 :min="1" :max="10000"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="床位费(元)" prop="bedFee">
                <el-input-number v-model="form.bedFee" controls-position="right"
                                 :precision="2"
                                 :min="0" :max="1000000"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="护理费(元)" prop="nursingFee">
                <el-input-number v-model="form.nursingFee" controls-position="right"
                                 :precision="2"
                                 :min="0" :max="1000000"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-form-item label="宣传照片" prop="publicityImgs">
          <image-upload v-model="form.publicityImgs"
                        :limit="5" :isShowTip="false"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listHealthResource,
  getHealthResource,
  delHealthResource,
  addHealthResource,
  updateHealthResource
} from "@/api/health/healthResource";
import {getHealthRegionTree} from "@/api/health/healthRegion";

export default {
  name: "HealthResource",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资源管理表格数据
      healthResourceList: [],
      // 区域树(一二三级)
      regionTree: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type: '',
        name: '',
        regionId: ''
      },
      // 表单参数
      form: {
        type: 0,
        facilities: null,
        publicityImg1: null,
        publicityImg2: null,
        publicityImg3: null,
        publicityImg4: null,
        publicityImg5: null
      },
      // 表单校验
      rules: {},
      facilityList: [
        '配套餐厅',
        '配套空调',
        '医养结合',
        '医疗康复',
        '接收异地老人'
      ],
      facilitiesArr: []
    };
  },
  computed: {
    region1Name() {
      return function (region1Id) {
        const region1 = this.regionTree.find(item => {
          return item.id == region1Id
        })
        return region1.name
      }

    }
  },
  created() {
    this.getRegionTree();
    this.getList();
  },
  methods: {
    //查询： 所有区域树
    getRegionTree() {
      getHealthRegionTree().then(resp => {
        this.regionTree = this.deleteEmptyChildren(resp.data);
      })
    },
    // 去除tree中 空 children
    deleteEmptyChildren(arr) {
      for (let i = arr.length; i--; i > 0) {
        if (arr[i].children && arr[i].children.length > 0) {
          this.deleteEmptyChildren(arr[i].children)
        } else {
          delete arr[i].children
        }
      }
      return arr
    },
    /** 查询资源管理列表 */
    getList() {
      this.loading = true;
      listHealthResource(this.queryParams).then(response => {
        this.healthResourceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        type: 0,
        name: null,
        cover: null,
        brief: '',
        phone: '',
        address: '',
        regionId: null,
        contact: '',
        facilities: null,
        bedAmount: 1,
        bedFee: 0,
        nursingFee: 0,
        publicityImgs: [],
        publicityImg1: null,
        publicityImg2: null,
        publicityImg3: null,
        publicityImg4: null,
        publicityImg5: null,
      };
      //清空临时的 养老设施数组
      this.facilitiesArr = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加养老资源";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getHealthResource(id).then(response => {
        this.form = response.data;
        // 处理图片集的格式：
        // 最多5个字符串，放入数组中
        this.form.publicityImgs = []
        if (this.form.publicityImg1 != null) {
          this.form.publicityImgs.push(this.form.publicityImg1);
        }
        if (this.form.publicityImg2 != null) {
          this.form.publicityImgs.push(this.form.publicityImg2);
        }
        if (this.form.publicityImg3 != null) {
          this.form.publicityImgs.push(this.form.publicityImg3);
        }
        if (this.form.publicityImg4 != null) {
          this.form.publicityImgs.push(this.form.publicityImg5);
        }
        if (this.form.publicityImg5 != null) {
          this.form.publicityImgs.push(this.form.publicityImg5);
        }
        //将数组转 字符串 ,
        this.form.publicityImgs = this.form.publicityImgs.join(',')

        this.open = true;
        this.title = "修改养老资源";
      });
    },
    /** 提交按钮 */
    submitForm() {
      //判断一下，如果有宣传图，就处理格式
      if (this.form.publicityImgs.length > 0) {
        const imgsUrlArr = this.form.publicityImgs.split(',');
        //拆分成5个字符串
        if (imgsUrlArr[0] != null || imgsUrlArr[0] != undefined) {
          this.form.publicityImg1 = imgsUrlArr[0];
        }
        if (imgsUrlArr[1] != null || imgsUrlArr[1] != undefined) {
          this.form.publicityImg2 = imgsUrlArr[1];
        }
        if (imgsUrlArr[2] != null || imgsUrlArr[2] != undefined) {
          this.form.publicityImg3 = imgsUrlArr[2];
        }
        if (imgsUrlArr[3] != null || imgsUrlArr[3] != undefined) {
          this.form.publicityImg4 = imgsUrlArr[3];
        }
        if (imgsUrlArr[4] != null || imgsUrlArr[4] != undefined) {
          this.form.publicityImg5 = imgsUrlArr[4];
        }
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateHealthResource(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addHealthResource(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除资源管理编号为"' + ids + '"的数据项？').then(function () {
        return delHealthResource(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('health/healthResource/export', {
        ...this.queryParams
      }, `healthResource_${new Date().getTime()}.xlsx`)
    },
    //养老配套设置复选框的change
    handleFacilitiesChange() {
      this.form.facilities = this.facilitiesArr.join(',')
    }
  }
};
</script>
